﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;

namespace Xejen.Communication.Http
{
    /// <summary>
    /// 表示Http请求结果
    /// </summary>
    /// <typeparam name="T">返回值的类型</typeparam>
    /// <creator>marc</creator>
    public class HttpResponse<T> : Result<T>
    {
        /// <summary>
        /// 字符编码：默认UTF-8
        /// </summary>
        [JsonIgnore]
        public Encoding Encoding { get; private set; } = Encoding.UTF8;

        /// <summary>
        /// 默认构造函数
        /// </summary>
        public HttpResponse()
        {

        }

        /// <summary>
        /// 默认构造函数
        /// </summary>
        /// <param name="encoding"><inheritdoc cref="Encoding" path="/summary"/></param>
        public HttpResponse(Encoding encoding = default)
        {
            SetEncoding(encoding);
        }

        /// <summary>
        /// 返回一个表示成功的<see cref="HttpResponse{T}"/>对象
        /// </summary>
        /// <param name="returnData"><inheritdoc cref="Result{T}.ReturnData" path="/summary"/></param>
        /// <param name="encoding"><inheritdoc cref="Encoding" path="/summary"/></param>
        public static HttpResponse<T> Success(T returnData, Encoding encoding = default)
        {
            HttpResponse<T> response = new HttpResponse<T>(encoding);
            response.ReturnData = returnData;
            response.Code = SuccessCode;

            return response;
        }

        /// <summary>
        /// 返回一个表示失败的<see cref="HttpResponse{T}"/>对象
        /// </summary>
        /// <param name="code"><inheritdoc cref="IResult.Code" path="/summary"/></param>
        /// <param name="exception"><inheritdoc cref="IResult.Exception" path="/summary"/></param>
        public static HttpResponse<T> Fail(int code, Exception exception = default)
        {
            return new HttpResponse<T>()
            {
                Code = code,
                Exception = exception,
            };
        }

        /// <summary>
        /// 设置编码
        /// </summary>
        /// <param name="encoding"><inheritdoc cref="Encoding" path="/summary"/></param>
        private void SetEncoding(Encoding encoding)
        {
            if (encoding == null)
            {
                return;
            }

            Encoding = encoding;
        }
    }
}
